import { isType } from "../utils"
class Children{
  _children = []
  _parent = null

  addChild( child, el = null , name = '' ){
    const to = isType(el, 'String') ? this.root.find( el ) : el
    child.render( to )
    child._parent = this
    child._name = name ? name : child._nodeTag
    this._children.push( child )
    return child
  }

  addChildTo( child, el = null , name = '' ){
    const to = $("<div></div>")
    const panel = isType(el, 'String') ? this.root.find( el ) : el
    child.render( to )
    child._parent = this
    child._name = name ? name : child._nodeTag

    panel.append( child.el )
    this._children.push( child )
    return child
  }

  hasChild( child ){
    const childTag = child._nodeTag
    return this._children.reduce((t, cld)=>{
      if( cld._nodeTag === childTag ){
        t = cld
      }
      return t
    }, null )
  }

  delChild( child ){
    this._removeTagChild(child._nodeTag)
  }

  pushChild( child ){
    if(!this.hasChild(child)){
      this._children.push( child )
    }
  }

  eachChildren( fn ){
    this._children.forEach( fn )
  }

  find(childName){
    const re = this._children.reduce( (t,child)=>{
      if( child._name && child._name === childName ){
        return [...t, child]
      }
      return t
    }, [])
    return re.length === 1 ? re[0] : ( re.length === 0 ? null : re )
  }

  findByClass(cls){
    const re = this._children.reduce( (t,child)=>{
      if( child.el && $(child.el).hasClass( cls ) ){
        return [...t, child]
      }
      return t
    }, [])
    return re.length === 1 ? re[0] : ( re.length === 0 ? null : re )
  }

  _removeTagChild( tag ){
    this._children = this._children.reduce((t, v)=>{
      return v._nodeTag === tag ? t : [...t,v]
    },[])
  }

  removeChild( child ){
    const tag = child._nodeTag
    this._removeTagChild( tag )
    child.remove()
  }

  remove(){
    const parent = this._parent
    parent && parent._removeTagChild( this._nodeTag )
    this.root?.remove()
  }
}

export default Children